package com.sk.waste.app.activitys

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import android.widget.ImageButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCDeviceUtil
import com.lc.smc.lib.utils.LCDialogUtil
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.BuildConfig
import com.sk.waste.app.R
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.fragments.MainFragment
import com.sk.waste.app.fragments.MarketFragment
import com.sk.waste.app.fragments.MerchantFragment
import com.sk.waste.app.fragments.MineFragment
import com.sk.waste.app.fragments.SpaceFragment
import com.sk.waste.app.utils.BaseUtil
import com.sk.waste.app.utils.LoginUtil
import com.sk.waste.app.utils.PermissionUtil
import com.sk.waste.app.utils.UpdateUtil
import com.sk.waste.app.views.CustomerDialog
import org.json.JSONObject


/**
 *  @time 2025/5/26  14:50
 *  @desc 首页
 */
class MainActivity : BaseActiivity() {

    @LCBindView(R.id.ac_main_top_layout)
    private lateinit var topLayout: View

    @LCBindView(R.id.ac_main_top_layout1)
    private lateinit var topLayout1: View

    @LCBindView(R.id.ac_main_location)
    private lateinit var ttvLocation: TextView

    @LCBindView(R.id.ac_main_push)
    lateinit var ttvPush: TextView

    @LCBindView(R.id.ac_main_customer)
    private lateinit var bttCustomer: ImageButton

    @LCBindView(R.id.ac_main_radiogroup)
    private lateinit var radioGroup: RadioGroup

    private var customerDialog: CustomerDialog? = null
    private var isRequestedLocation = false


    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_main)
        super.onCreate(savedInstanceState)
//        setStataBar()
        initView()
//        startLocation()
        showPermissionDialog()
        toogleFragment(MainFragment::class.java)
        checkUpdate()
    }

    override fun onResume() {
        super.onResume()
        if (!isRequestedLocation) {
            startLocation()
        }
        aotuLogin()
    }

    private fun setStataBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            val gradientDrawable = resources.getDrawable(R.drawable.bg_status_gradient, null) as GradientDrawable
            window.statusBarColor = Color.TRANSPARENT // 必须先设为透明
            window.setBackgroundDrawable(gradientDrawable) // 设置背景（实际影响状态栏）
        }
    }

    /**
     *  @time 2024/10/8  9:49
     *  @author Im_jingwei
     *  @desc app请求权限回调
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtil.instance.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun initView() {
        radioGroup.setOnCheckedChangeListener(onTabListener)

        bttCustomer.setOnClickListener {
            showCustomerAlert()
        }
    }

    private val onTabListener = RadioGroup.OnCheckedChangeListener { group, checkedId ->
        when (checkedId) {
            R.id.radiobutton0 -> {
                ttvLocation.visibility = View.VISIBLE
                bttCustomer.visibility = View.GONE
                topLayout.visibility = View.VISIBLE
                topLayout1.visibility = View.GONE
                ttvPush.visibility = View.GONE
                toogleFragment(MainFragment::class.java)
            }

            R.id.radiobutton1 -> {
                ttvLocation.visibility = View.GONE
                bttCustomer.visibility = View.GONE
                topLayout.visibility = View.VISIBLE
                topLayout1.visibility = View.GONE
                ttvPush.visibility = View.GONE
                toogleFragment(MarketFragment::class.java)
            }

            R.id.radiobutton2 -> {
                ttvLocation.visibility = View.GONE
                bttCustomer.visibility = View.GONE
                topLayout.visibility = View.VISIBLE
                topLayout1.visibility = View.GONE
                ttvPush.visibility = View.VISIBLE
                toogleFragment(SpaceFragment::class.java)
            }

            R.id.radiobutton3 -> {
                ttvLocation.visibility = View.GONE
                bttCustomer.visibility = View.GONE
                topLayout.visibility = View.VISIBLE
                topLayout1.visibility = View.GONE
                ttvPush.visibility = View.GONE
                toogleFragment(MerchantFragment::class.java)
            }

            R.id.radiobutton4 -> {
                ttvLocation.visibility = View.GONE
                bttCustomer.visibility = View.VISIBLE
                topLayout.visibility = View.GONE
                topLayout1.visibility = View.VISIBLE
                ttvPush.visibility = View.GONE
                toogleFragment(MineFragment::class.java)
            }
        }
    }

    /**
     *  @time 2025/4/23  18:25
     *  @desc 切换fragment
     */
    private fun toogleFragment(c: Class<out Fragment?>) {
        val manager = supportFragmentManager
        val tag = c.name
        val transaction = manager.beginTransaction()
        var fragment = manager.findFragmentByTag(tag)
        if (fragment == null) {
            fragment = c.newInstance()
            // 替换时保留Fragment,以便复用
            transaction.add(R.id.content_frame, fragment!!, tag)
        }
        // 遍历存在的Fragment,隐藏其他Fragment
        val fragments = manager.fragments
        if (fragments != null) for (fm in fragments) if (fm != fragment) transaction.hide(fm)
        transaction.show(fragment!!)
        transaction.commit()
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 拨打客服
     */
    private fun showCustomerAlert() {
        if (customerDialog == null) {
            customerDialog = CustomerDialog(mContext)
            customerDialog!!.setOnclickListener(mDeleteOnclickListener)
        }
        customerDialog!!.show()
    }


    private val mDeleteOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {
        }

        override fun onPositiveClick(vararg args: Any?) {
            val number: String = args[0].toString().trim()
//            val intent = Intent(Intent.ACTION_CALL)
//            intent.setData(Uri.parse("tel:$number"))
//            startActivity(intent)
            BaseUtil.callPhone(mContext, number)
        }
    }

    /**
     *  @time 2025/1/24  15:44
     *  @author Im_jingwei
     *  @desc 开始定位
     */
    fun startLocation() {
        val mLocationClient = AMapLocationClient(this)
        val locationClientOption = AMapLocationClientOption()
        locationClientOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        locationClientOption.isGpsFirst = true
        locationClientOption.isSensorEnable = true
        locationClientOption.isNeedAddress = true
        mLocationClient.setLocationOption(locationClientOption)
        mLocationClient.setLocationListener {
//            Log.d("LCLOG_MAPLOCATION", "location: $it")
            isRequestedLocation = true
            ttvLocation.text = it.city
            MyApplication.instance.setLocaiton(it.city)
        }
        mLocationClient.startLocation()
    }


    /**
     *  @time 2025/9/9  20:05
     *  @author Im_jingwei
     *  @desc 自动登录
     */
    private fun aotuLogin() {
        if (LCDeviceUtil.hasNetWork(mContext)) {
            val userAccount = LCSPUtil[mContext, AppConfig.SP_USER_ACCOUNT]
            val userPass = LCSPUtil[mContext, AppConfig.SP_USER_PASSWORD]
            if (!TextUtils.isEmpty(userAccount)) {
                val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_LOGIN
                val json = JSONObject()
                json.put("account", userAccount)//用户名称
                json.put("password", userPass)//用户密码
                LoginUtil.loginSubmit(0, this, url, json.toString(), loginCallBack)
            }
        } else {
            showToast("没有网络，请检测网络情况！")
        }
    }

    private val loginCallBack = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            runOnUiThread {
                // 获取当前显示的 Fragment
                var fragment = supportFragmentManager.findFragmentByTag(MainFragment::class.java.name)
                if (fragment is MainFragment) {
                    (fragment as MainFragment?)!!.refreshData()
                }
            }
        }
    }

    private fun showPermissionDialog() {
        val isShowProvacy = LCSPUtil[mContext, AppConfig.SP_USER_PERSSION]
        if (!LCBaseUtil.isNull(isShowProvacy)) {
            return
        }
//        PermissionUtil.instance.requesetPermission(this)
        val dialog = LCDialogUtil(mContext)
        var msg = "尊敬的用户，本系统所申请的包括：\n " +
                "1.相机权限，用户可自定义头像\n" +
                "2.媒体权限，用户可自定义头像\n" +
                "3.位置权限，展示用户当前所在位置\n" +
                "4.电话权限，可点击电话号码拨打电话"
        dialog.setTileAndContent("权限申请说明", msg)
        dialog.setButtonOnclickListener {
            LCSPUtil.save(mContext, AppConfig.SP_USER_PERSSION, "true")
            PermissionUtil.instance.requesetPermission(this)
        }
        dialog.show()
    }

    private fun checkUpdate() {
        val isShowProvacy = LCSPUtil[mContext, AppConfig.SP_USER_PERSSION]
        if (!LCBaseUtil.isNull(isShowProvacy)) {
            UpdateUtil.checkUpdate(mContext, false)
        }
    }

}